// pages/broadcast/broadcast.js
var server;
const DeviceName = 'Shenyi-Ble';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceName: DeviceName,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  startBroadcast: function () {
    this.openBle();
  },

  stopBroadcast: function () {
    server.stopAdvertising({
      success: (res) => {
        console.log('stopBroadcast success');
        console.warn(res);
      },
      fail: (res) => {
        console.log('stopBroadcast failed');
        console.warn(res);
      },
      complete: (res) => {
        console.debug('stopBroadcast completed');
      }
    });
  },

  // 低功耗蓝牙广播测试
  openBle() {
    wx.openBluetoothAdapter({
      mode: 'peripheral',
      success: (res) => {
        console.info('Bluetooth adapter opened');
        console.log('Creating BLEPeripheralServer');
        wx.createBLEPeripheralServer({
          success: (res) => {
            console.info('createBLEPeripheralServer successed', res);
            // let server = res.server;
            server = res.server;
            console.log(server);
            let uuid1 = '0000af8e-0000-1000-8000-00805f9b34fb';
            // let uuid2 = '0000ae8f-0000-1000-8000-00805f9b34fb';
            let buff = [0x0a, 0x0b, 0x0c, 0x0d];

            server.startAdvertising({
              advertiseRequest: {
                connectable: true,
                deviceName: DeviceName,
                // serviceUuids: [
                //   uuid1,
                //   uuid2
                // ],
                serviceUuids: [
                  uuid1
                ],
                manufacturerData: [{
                  manufacturerId: 0x01AC,
                  manufacturerSpecificData: buff
                }]
              }
            }).then(
              (res) => {
                console.log('Adverstising.. ', res);
              },
              (res) => {
                console.warn('Advertising failed', res);
              });
          },
          fail: (res) => {
            console.warn('createBLEPeripheralServer failed');
          },
          complete: (res) => {
            console.debug('createBLEPeripheralServer completed');
          }
        });
      },
      fail: (res) => {
        console.log('openBluetoothAdapter failed');
        console.warn(res);
      },
      complete: (res) => {
        console.debug('openBluetoothAdapter completed');
      },
    });
  }
})